﻿using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using MWS.Processing.Interfaces;

namespace MWS.Processing.Serializers
{
    public class XmlSerializer : IXmlSerializer
    {
        public XElement Serialize<T>(T item)
        {
            var dcs = new DataContractSerializer(typeof (T));
            var ms = new MemoryStream();
            dcs.WriteObject(ms, item);
            ms.Position = 0;
            var doc = XElement.Load(ms);
            ms.Close();
            return doc;
        }

        public T Deserialize<T>(XElement item)
        {
            var ms = new MemoryStream();
            ms.Write(Encoding.UTF8.GetBytes(item.ToString()), 0, item.ToString().Length);
            ms.Position = 0;
            var reader = XmlDictionaryReader.CreateTextReader(ms, new XmlDictionaryReaderQuotas());
            var ser = new DataContractSerializer(typeof (T));
            var obj = (T) ser.ReadObject(reader, true);
            reader.Close();
            ms.Close();
            return obj;
        }
    }
}